<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useTokenStore } from '@/stores/token.js'
import { useStudentStore } from '@/stores/student.js'
import LoginExpiredModal from '@/components/LoginExpiredModal.vue'

const router = useRouter()
const tokenStore = useTokenStore()
const studentStore = useStudentStore()
const loginExpiredModal = ref(null)

// 处理登录过期
const handleLoginExpired = () => {
  try {
    console.log('处理登录过期')
    // 清除token和用户信息
    tokenStore.removeToken()
    studentStore.removeStudentInfo()
    
    console.log('已清除用户信息和token')
    
    // 跳转到登录页
    router.push('/login').then(() => {
      console.log('成功跳转到登录页')
    }).catch((error) => {
      console.error('跳转登录页失败:', error)
      // 如果路由跳转失败，尝试强制刷新页面到登录页
      window.location.href = '/login'
    })
  } catch (error) {
    console.error('处理登录过期时出错:', error)
    // 出错时也强制跳转到登录页
    window.location.href = '/login'
  }
}

// 处理弹窗隐藏
const handleModalHide = () => {
  console.log('登录失效弹窗已隐藏')
}

// 全局显示登录失效弹窗的方法
const showLoginExpiredModal = () => {
  if (loginExpiredModal.value) {
    loginExpiredModal.value.show()
  }
}

// 在window对象上挂载全局方法，供loginExpiredManager调用
onMounted(() => {
  window.showLoginExpiredModal = showLoginExpiredModal
})
</script>

<template>
  <div id="app">
    <router-view />
    <!-- 全局登录失效弹窗 -->
    <LoginExpiredModal 
      ref="loginExpiredModal" 
      @confirm="handleLoginExpired" 
      @hide="handleModalHide" 
    />
  </div>
</template>

<style scoped>

</style>
